<?php
/**
 * Created by PhpStorm.
 * User: Yieong
 * Date: 14-10-16
 * Time: 上午9:31
 */

class PubDbLink {
    private $dbConnection = false;

    public function __construct($dbConfig, $selectDb=''){
        try{
            if(is_string($dbConfig)){
                $this->dbConnection = Yii::app()->$dbConfig;
            }else if(is_array($dbConfig)){
                $this->dbConnection = new LibDatabase($dbConfig['dsn'], $dbConfig['username'], $dbConfig['password']);
                $this->dbConnection->charset = 'utf8';
            }

            if($this->dbConnection !== false && !empty($selectDb)){           	
                $this->dbConnection->selectDB($selectDb);
            }           
        }catch (Exception $e){
            $this->dbConnection = false;
        }
    }

    public function query($sql, $args=array(), $col=null){
        try{
            if($this->dbConnection !== false){
                $tmp = $this->dbConnection->getAll($sql, $args);
                if(isset($col)) {
                    $col = strval($col);
                    $result = array();
                    foreach($tmp as $v){
                        $result[] = $v[$col];
                    }
                }else{
                    $result = $tmp;
                }

                return $result;
            }else{
                throw new Exception('Connection is false');
            }
        }catch (Exception $e){
            return array();
        }
    }

    public function tableExist($table){
        try{
            if($this->dbConnection !== false){
                $result = $this->dbConnection->query("SHOW TABLES LIKE :table", array(':table'=>$table));
                return (count($result) > 0);
            }else{
                return false;
            }
        }catch (Exception $e){
            return false;
        }
    }
    
    
    public function execute($sql, $args=array()){
        try{
            if($this->dbConnection !== false)
                return $this->dbConnection->execute($sql, $args);
            else
                return array();
        }catch (Exception $e){
            echo $e->getMessage();die;
            return array();
        }
    }

    public function getLink(){
        return $this->dbConnection;
    }

    public function getDict($sql, $key,$value,$args=array()){
        try{
            if($this->dbConnection !== false)
                return $this->dbConnection->getAllAsMap($sql, $key,$value,$args);
            else
                return array();
        }catch (Exception $e){
            echo $e->getMessage();die;
            return array();
        }
    }

} 
